--[[
Copyright:www.vxinyou.com
Author:xuerui
CreateTime:2013-06-18
Description:列表
--]]

local clsListView = Class("lua/cc/clsNode.lua"):Inherit()

function clsListView:create(args)
	self._root = CCTableView:create(CCSizeMake(args.width, args.height))
	self._root:setDelegate()
	if args.style and style == cc.SCROLLVIEW_DIRECTION_HORIZONTAL then
		self._root:setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL)		
	else
		self._root:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
		self._root:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN)
	end	
	self.list={}
	self.nRefreshTyp = 'top' --'top'/'bottom'	
	self.width = args.width
	self.height = args.height	
end

function clsListView:doDistinctConfig()
	if not self.args then
		return 
	end
	if self.args.scriptHandler then
		self:registerScriptHandler(self.args.scriptHandler.nFunID,self.args.scriptHandler.nScriptEventType)
	end
end
function clsListView:setSelfConfig(Type, newConfig)
	assert(Type)
	assert(newConfig)
	local configType = Type
	if configType == "registerScriptHandler" then
		self.args.scriptHandler = newConfig.scriptHandler
	elseif configType == "setPosition" then
		self.args.x = newConfig.x
		self.args.y = newConfig.y
	elseif configType == "setContentSize" then
		self.args.cx = newConfig.cx
		self.args.cy = newConfig.cy
	end
end

function clsListView:registerScriptHandler(nFunID,nScriptEventType)
	self._root:registerScriptHandler(nFunID,nScriptEventType)
	self:setSelfConfig("registerScriptHandler", {scriptHandler = {nFunID = nFunID, nScriptEventType = nScriptEventType}})
end

function clsListView:addItem(data,create,click)
	local o = {}
	o["data"] = data
	o["create"] = create
	o["size"] = {}
	o["click"] = click	
	o["valid"] = false --节点未被创建
	table.insert(self.list,o)
	local idx = #self.list
	local _, sx, sy = create( idx, data,true )	
	self:setItemSize( idx, { width = sx, height = sy } )
	return #self.list
end

function clsListView:updateItemAtIndex(idx,data,create,click)
	local o = self.list[idx]
	if o then 
		o["data"] = data
		o["create"] = create
		o["size"] = {}
		o["click"] = click	
		o["valid"] = false --节点未被创建
		local _, sx, sy = create( idx, data,true )				
		self:setItemSize( idx, { width = sx, height = sy } )
	else
		self:addItem(data,create,click)
	end
end

--Input:idx：索引，从1开始,size：{width, height}，按需传入
function clsListView:setItemSize( idx, size )
	obj = self.list[idx]['size']
	for k,v in pairs(size) do
		obj[k] = v
	end
end

function clsListView:reload()
	self._root:reloadData()				
end		

function clsListView:clear()
	self.list = {}
end

function clsListView:size()
	assert(self.list)
	return #self.list
end

function clsListView:OnTopRefresh()
end

function clsListView:OnBottomRefresh()
end		

function clsListView:onScroll(ptMax,ptMin,pt)
end

function clsListView:scrollViewEndScroll(view,idx)
	--[[local cell = view:dequeueCell(idx)	
	if cell then
		cell:removeAllChildrenWithCleanup(true)
	end	--]]	
end

function clsListView:insertCellAtIndex(idx)
	self._root:insertCellAtIndex(idx)
end

--[[
修改Cell大小，一般因有图片下载等回调导致。
参数：
idx：索引，从1开始
force：因避免陷入死循环，每个cell默认仅可被修改一次，如需要多次，需要传入参数force=true
]]
--[[
function clsListView:updateCellAtIndex(idx, force)
	--self._root:updateCellAtIndex(idx)
	local list = self.list[idx]
	if list then
		if list["valid"] == true then	
			if list.refresh and not force then
				return
			end
			
			list.refresh = true
			
			local node, sx, sy = list.create(idx,list.data,true)
			node:getCOObj():retain()
			list["node"] = node
			self:setItemSize( idx, { width = sx, height = sy } )
			--self._root:updateCellBySize(idx)
			--self._root:updateCellAtIndex(idx - 1,true)
		end
	end
end	
]]--

function clsListView:scrollViewDidScroll(view)
	--[[
	local pt = view:getContentOffset()
	local ptmin = view:minContainerOffset()
	local ptmax = view:maxContainerOffset()
	
	if self.bNeedRefresh == false and pt.y < ptmax.y and pt.y <= ptmin.y - 18 then
		self.nRefreshTyp = 'top' --到顶刷新
		self.bNeedRefresh = true
		--showLoading()
	elseif self.bNeedRefresh == false and pt.y > ptmin.y and pt.y >= ptmax.y + 18 then
		MOD_DEBUG.d(pt.y .. ' : ' .. ptmin.y .. ' : ' .. ptmax.y)
		self.nRefreshTyp = 'bottom' --到底刷新
		self.bNeedRefresh = true
	else
		self:onScroll(view)
	end
	if self.bNeedRefresh == true then	
		if pt.y >= ptmin.y and self.nRefreshTyp == 'top'  then	
			f_delay_do2(self._root,self.OnTopRefresh,nil,0.5)			
			self.bNeedRefresh = false	
			--self.loading:removeAllChildrenWithCleanup(true)		
		elseif pt.y <= ptmax.y and self.nRefreshTyp == 'bottom'  then
			f_delay_do2(self._root,self.OnBottomRefresh,nil,0.5)		
			self.bNeedRefresh = false				
		end				
	end	
	]]--	
end	


function clsListView:tableCellTouched(table,cell)
    --print("cell touched at index: " .. cell:getIdx())
	local idx = cell:getIdx() + 1
	if self.list[idx]["click"] then	
		self.list[idx]["click"](idx,self.list[idx]["data"])
	end
	--self:OnClickItem(cell:getIdx() + 1)
end

function clsListView:cellSizeForTable(table,idx)
	--local o = ItemList[idx+1]:getContentSize()
	local o = self.list[idx+1]["size"]
	return o.height,o.width
	--return 0
end

function clsListView:tableCellAtIndex(table, idx)
	local cell = table:dequeueCell()
	
	local function createItem(parent)
		local obj = self.list[idx+1]		
		obj["valid"] = true
		local o,x,y = obj["create"](idx+1,obj["data"])
		--local o = obj["node"]	
		
		o:setAnchorPoint(0,0)
		o:setPosition(0,0)
		--[[
		local size = obj["size"]	
		if o and size then
			o:setPosition(0,size.height)
		end
		]]
		--local node = o:getCOObj()				
		-- 更新大小，修正y坐标
		--[[if size then
			node:setPosition(0,size.height)
		end--]]
		--[[if x then		
			node:setPosition(0,y)			
		end--]]
		--cell:addChild(o)
		--cell:getCOObj():addChild(o)
		--cell:addChild(node)
		--node:release()	
		parent:addChild(o)	
	end
	if cell == nil then
		--cell = createListCell():getCOObj()
		local parent = createListCell()
		cell = parent:getCOObj()
		createItem(parent)			
		--d('idx: ' .. idx .. ' id: ' .. self.list[idx+1]["data"]['id'])
	--[[else
		cell = createListCell():getCOObj()
		cell:removeAllChildrenWithCleanup(true)
		createItem(cell)--]]		
	end
	return cell
end

function clsListView:numberOfCellsInTableView(table)
	assert(self.list)
	--MOD_DEBUG.d(#self.list)
	return #self.list
	--return 0
end


function clsListView:setPosition(x,y)
	local size = self:getContentSize()	
	local new_x = x
	local new_y = y
	if self.ax == 0.5 then
		new_x = x - size.width/2
	elseif self.ax == 1 then
		new_x = x - size.width
	end
	
	if self.ay == 0.5 then
		new_y = y - size.height/2
	elseif self.ay == 1 then
		new_y = y - size.height
	end		
	self._root:setPosition(ccp(new_x,new_y))
	self:setSelfConfig("setPosition", {x = x, y = y})
end

function clsListView:setContentSize(width, height)
	self._root:setViewSize(CCSizeMake(width,height))	
	local x,y = self:getPosition()
	self:setPosition(x,y)
	self:setSelfConfig("setContentSize", {cx = width, cy = height})
end

function getClass()
	return clsListView
end
